<?php


namespace modules\sys\service\impl;


use application\core\Request;
use application\core\Result;
use modules\sys\mapper\FieldMapper;
use modules\sys\mapper\TableMapper;
use modules\sys\service\PathReplaceService;

class PathReplaceServiceImpl implements PathReplaceService
{

    function lists(): array
    {
        $tableRs = TableMapper::lists();
        $tableRs = array_column($tableRs, NULL, 'table_name');
        $data = Request::json();
        $lists = FieldMapper::ListsAllowReplace([
            'is_allow_replace' => 1,
            'table_name' => $data['table_name'] ?? '',
            'field_name' => $data['field_name'] ?? '',
            'ids' => ''
        ]);
        foreach ($lists as $k => $v) {
            $lists[$k]['table_remarks'] = $tableRs[$v['table_name']]['table_remarks'];
        }
        return Result::success(false, $lists ?? []);
    }

    function doReplace(array $data): array
    {
        $ids = $data['ids'];
        $oriPath = $data['ori_path'];
        $newPath = $data['new_path'];
        if (substr($oriPath, 0, 7) != "http://" && substr($oriPath, 0, 7) != "https://") {
            return Result::fail(false, [], "原路径必须以http://或者https://开头");
        }
        if (substr($newPath, 0, 7) != "http://" && substr($newPath, 0, 7) != "https://") {
            return Result::fail(false, [], "新路径必须以http://或者https://开头");
        }
        if ($oriPath == $newPath) {
            return Result::fail(false, [], "新路径和原路径不能一样！");
        }
        $totalReplace = 0;
        $lists = FieldMapper::ListsAllowReplace([
            'is_allow_replace' => 1,
            'table_name' => '',
            'field_name' => '',
            'ids' => $ids
        ]);
        foreach ($lists as $v) {
            $num = FieldMapper::replacePath([
                'table_name' => $v['table_name'],
                'field_name' => $v['field_name'],
                'ori_path' => $oriPath,
                'new_path' => $newPath
            ]);
            $totalReplace += $num;
        }
        return Result::success(true, [], "本次一共替换了<span style='color: red'>【" . $totalReplace . "】</span>处");
    }
}